<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" row-key="tableId" :request-api="listTableApi">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="['tool:gen:code']" :disabled="!scope.isSelected" icon="CirclePlus" @click="handleGenTable()">
          生成
        </el-button>
        <el-button type="primary" v-auth="['tool:gen:import']" icon="Upload" plain @click="batchAdd"> 导入表 </el-button>
        <el-button
          type="danger"
          v-auth="['system:user:remove']"
          icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link icon="View" v-auth="['tool:gen:query']" @click="openDialog(1, '代码预览', scope.row)"> 预览 </el-button>
        <el-button type="primary" link icon="EditPen" v-auth="['tool:gen:edit']" @click="toDetail(scope.row)"> 编辑 </el-button>
        <el-button type="primary" link icon="Delete" v-auth="['tool:gen:remove']" @click="deleteRole(scope.row)"> 删除 </el-button>
        <el-button type="primary" link icon="Refresh" v-auth="['tool:gen:edit']" @click="handleSyncDb(scope.row)"> 同步 </el-button>
        <el-button type="primary" link icon="Download" v-auth="['tool:gen:code']" @click="handleGenTable(scope.row)"> 生成代码 </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef">
      <template #default="{ parameter }">
        <div class="dialog-slot-c">
          <el-tabs v-model="parameter.model.activeName" type="border-card">
            <el-tab-pane
              v-for="(value, key) in parameter.model.data"
              :label="key.toString().substring(key.toString().lastIndexOf('/') + 1, key.toString().indexOf('.vm'))"
              :name="key.toString().substring(key.toString().lastIndexOf('/') + 1, key.toString().indexOf('.vm'))"
              :key="value"
            >
              <preview-code
                :code="value"
                :type="
                  key
                    .toString()
                    .substring(key.toString().lastIndexOf('/') + 1, key.toString().indexOf('.vm'))
                    .split('.')[1] == 'vue'
                    ? 'ts'
                    : key
                        .toString()
                        .substring(key.toString().lastIndexOf('/') + 1, key.toString().indexOf('.vm'))
                        .split('.')[1] || key.toString().substring(key.toString().lastIndexOf('/') + 1, key.toString().indexOf('.vm'))
                "
              >
              </preview-code>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
    </FormDialog>
    <TableDialog ref="tableDialogRef" @submit-form="submitForm" />
  </div>
</template>

<script setup lang="tsx" name="Role">
import { useHandleData } from '@/hooks/useHandleData'
import { useDownload } from '@/hooks/useDownload'

import FormDialog from '@/components/CustomDialog/index.vue'
import TableDialog from '@/components/TableDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import PreviewCode from '@/components/Highlight/index.vue'
import { listTableApi, batchGenCodeApi, listDbTableApi, importTableApi, previewTableApi, delTableApi, synchDbApi } from '@/api/modules/tool/gen'
// ProTable 实例
const proTable = ref<ProTableInstance>()
const router = useRouter()
// 跳转详情页
const toDetail = (row: { tableId: any }) => {
  router.push(`/tool/tool-edit/index/${row.tableId}`)
}

let preview = ref({
  data: {},
  activeName: 'domain.java'
})

// 表格弹框提交
const submitForm = () => {
  proTable.value?.getTableList()
}

// 删除角色信息信息
const deleteRole = async (params: any) => {
  await useHandleData(delTableApi, params.tableId, `删除【${params.tableComment}】信息`)
  proTable.value?.getTableList()
}

// 批量删除角色信息信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(delTableApi, ids, '删除所选信息')
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}

// 批量添加表信息
const tableDialogRef = ref<InstanceType<typeof TableDialog> | null>(null)
const batchAdd = () => {
  const params = {
    title: '导入表',
    width: 880,
    toolButton: false,
    rowKey: 'tableName',
    columns: subColumns,
    api: importTableApi,
    getTableList: listDbTableApi,
    backTableList: listTableApi
  }
  tableDialogRef.value?.openDialog(params)
}

//  生成代码
const handleGenTable = (_row?: { tableId: string }) => {
  let tableIdArr: any[] | undefined = proTable.value?.selectedList.map(item => item.tableId)
  let tableIds = _row?.tableId || tableIdArr?.join(',')
  useDownload(batchGenCodeApi, '生成代码', tableIds, false, 'zip', 'eco.zip')
}

// 同步表数据
const handleSyncDb = async (_row: { tableId: any; tableName: any }) => {
  await useHandleData(synchDbApi, _row.tableId, `要强制同步【${_row.tableName}】信息`)
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (_type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.tableId) {
    res = await previewTableApi(row?.tableId || null)
    preview.value.data = res.data
    preview.value.activeName = 'domain.java'
  }
  const params = {
    title,
    model: preview
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 60 },
  { type: 'index', label: '序号', width: 70 },
  {
    prop: 'tableName',
    label: '表名',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'tableComment',
    label: '表描述',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'className',
    label: '实体',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'createTime',
    label: '创建时间',
    search: {
      el: 'date-picker',
      props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    }
  },
  { prop: 'operation', label: '操作', width: 400 }
])
// 表格配置项
const subColumns: ColumnProps[] = [
  { type: 'selection', fixed: 'left', width: 60 },
  {
    prop: 'tableName',
    label: '表名称',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'tableComment',
    label: '表描述',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'createTime',
    label: '创建时间'
  }
]
</script>
